/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: TestProducer
 * Author:   pc
 * Date:     2019/9/2 11:09
 * Description: 生产者
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.example.rabbitmqdemo.rabbit;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.rabbitmqdemo.Repository.CommodityRepository;
import com.example.rabbitmqdemo.config.QuartzConfig;
import com.example.rabbitmqdemo.entity.JobEntity;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 〈功能：〉<br>
 * 〈生产者〉
 *
 * @author liuhaoran
 * @create 2019/9/2 11:09
 * @since 1.0.0
 */
@Component
@Slf4j
@Configuration
public class TestProducer {
	@Autowired
	CommodityRepository commoditymapper;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private QuartzConfig quartzConfig;

	public void send(String queueName) throws JSONException {
		ValueOperations<String, Map<String, Object>> operations = redisTemplate.opsForValue();
		Map<String, Object> map = new HashMap<String, Object>();
		Message message, order_information_message;
		int commodity_stock;
		boolean hasKey = redisTemplate.hasKey("Spike_stock");
		if (hasKey) {
			Object StrMapObj = operations.get("Spike_stock");
			commodity_stock = Integer.parseInt(((Map) StrMapObj).get("Spike_stock").toString());
			if (commodity_stock != 0) {
				commodity_stock--;
				map.put("Spike_stock", commodity_stock);
				operations.set("Spike_stock", map, 1000, TimeUnit.SECONDS);
				JSONObject jsonObject = new JSONObject();
				// 返回给消费者的信息
				jsonObject.put("successmsgsuccess", "用户信息：恭喜您抢到商品你的订单编号为：" + System.currentTimeMillis());
				String jsonString = jsonObject.toJSONString();
				// 保存给后台的数据
				JSONObject jsonObjectOrder = new JSONObject();
				jsonObjectOrder.put("id", System.currentTimeMillis());
				jsonObjectOrder.put("order_number", System.currentTimeMillis());
				String jsonStringorder = jsonObject.toJSONString();
				operations.set("commodityOrder" + commodity_stock, jsonObjectOrder, 60 * 60 * 12, TimeUnit.SECONDS);
				// 生产者发送消息的时候需要设置消息id
				message = MessageBuilder.withBody(jsonString.getBytes())
						.setDeliveryMode(MessageDeliveryMode.PERSISTENT)
						.setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
						.build();
				rabbitTemplate.convertAndSend(queueName, message);
				System.out.println("管理信息：当前库存:" + commodity_stock);
			} else {
				SchedulerFactory factory = new StdSchedulerFactory();
				try {
					Scheduler scheduler = factory.getScheduler();
					JobEntity job = new JobEntity();
					job.setName("QuartzTestTask");
					job.setGroup("quartzTest");
					job.setCron("0/5 * * * * ?");
					quartzConfig.getTrigger(job);
					scheduler.scheduleJob(quartzConfig.quatzTestTaskDetail(), quartzConfig.getTrigger(job));
					scheduler.start();
//					scheduler.standby(); //调度器挂起，挂起后可以通过 start 重启
//					// 立即关闭调度器，关闭后，不能重启
//					scheduler.shutdown();
//
//					// true:等待所有的job都执行完，然后再关闭scheduler
//					// false:立即关闭scheduler
//					scheduler.shutdown(true);
//					scheduler.isShutdown();  //是否关闭了
//					scheduler.isStarted();  //是否启动了
//					scheduler.isInStandbyMode(); //是否挂起了
				} catch (SchedulerException e) {
					e.printStackTrace();
				} finally {
					System.out.println("无法存储Job：已经存储了相同标识");
				}

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("failuremsg：", "活动结束");
				String jsonString = jsonObject.toJSONString();
				// 生产者发送消息的时候需要设置消息id
				message = MessageBuilder.withBody(jsonString.getBytes())
						.setDeliveryMode(MessageDeliveryMode.PERSISTENT)
						.setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
						.build();
				//rabbitTemplate.convertAndSend(queueName, message);
				// 保存的数据
				for (int i = 0; i < 5; i++) {
					Object StrMapObjOrder = operations.get("commodityOrder" + i);
					System.out.println(StrMapObjOrder);
				}
				//触发定时器,30分钟内没有付款删除数据释放库存,付款成功保存到数据库
				// 3. 创建scheduler

			}
			//String json= JSON.toJSONString(StrMapObj);
		} else {
			map.put("Spike_stock", "5");
			ListOperations<String, Object> lo = redisTemplate.opsForList();
			operations.set("Spike_stock", map, 100, TimeUnit.SECONDS);
		}
	}
}